package com.easthome.controller;

import com.easthome.constant.MessageConstant;
import com.easthome.constant.RedisMessageConstant;
import com.easthome.result.Result;
import com.easthome.service.OrderService;
import com.easthome.util.SMSUtils;
import com.easthome.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping("/sendMessage")
public class SendValidateCodeController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private JedisPool jedisPool;

    /**
     * 发送验证码
     * 接收参数为手机号
     * 调用工具类 ValidateCodeUtils 产生随机数
     * SMSUtils 发送
     * 存储在redis中 有效期为五分钟
     */
    @GetMapping("/sendValidateCode")
    public Result sendValidateCode(String phone) {
        Integer code = ValidateCodeUtils.generateValidateCode(4);

        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, phone, code + "");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        //发送成功
        Jedis jedis = jedisPool.getResource();
        jedis.setex(RedisMessageConstant.SENDTYPE_ORDER+":"+phone, 300, code + "");
        jedis.close();
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }
}
